﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using ThuPhap.Models;

namespace ThuPhap
{
    public partial class FontPage : PhoneApplicationPage
    {
        private int index;
        public delegate void FinishSelectedDelegate(FontFamily Font);
        public static event FinishSelectedDelegate FinishedSelectedFontEvent;
        public FontPage()
        {
            InitializeComponent();
            DataContext = App.FontViewModel;
        }

        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.FontViewModel.IsDataLoaded)
            {
                App.FontViewModel.LoadData();
            }
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            string source = string.Empty;
            if (NavigationContext.QueryString.TryGetValue("source", out source))
            {
                //int index = int.Parse(position);

                if (!App.FontViewModel.IsDataLoaded)
                {
                    App.FontViewModel.LoadData();
                }

                source = "/ThuPhap;component/Resources/Fonts/" + source.Replace("0","#");

                for (int i = 0; i < App.FontViewModel.Items.Count; i++)
                {
                    if (App.FontViewModel.Items[i].FontFamily.Source == source)
                    {
                        this.index = i;
                        var item = App.FontViewModel.Items[i];
                        //this.FontListBox.SelectedItem = item;
                        this.FontListBox.SelectedIndex = i;
                        this.FontListBox.ScrollIntoView(this.FontListBox.Items[i]);
                        
                        this.FontListBox.UpdateLayout();
                        break;
                    }
                }
                
                
            }
        }

        private void FontListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (FinishedSelectedFontEvent != null)
            {
                int index = FontListBox.SelectedIndex;
                if (index != this.index)
                {
                var font = FontListBox.SelectedItem as FontFamilyManage;
                FinishedSelectedFontEvent(font.FontFamily);
                this.NavigationService.GoBack();
                }


            }
        }
    }
}